﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TFSBugTracking.PasswordProtector
{
    class Program
    {
        static void Main(string[] args)
        {
            
            if (args.Length == 0)
                PrintHelp();
            if ( args.Contains("-?"))
                PrintHelp();

            string user, pass = null;

            string[] uap =GetUserAndPass(args);
            SetUserAndPassInFile(uap, "UserMappings.xml");

        }

        private static void SetUserAndPassInFile(string[] userAndPass, string usermappingsXml)
        {
            var mappings = global::TFSBugTracking.TfsImpersonationMap.GetMappings(usermappingsXml);
            var map = from entry in mappings  
                      where entry.TargetUserName == userAndPass[0] 
                      select  entry;

            if ( map.Count() == 0)
                Console.WriteLine("target User {0} not found in {1}",userAndPass[0],usermappingsXml);

            foreach (TfsImpersonationMap tfsImpersonationMap in map)
                tfsImpersonationMap.TargetPassword = userAndPass[1].Encrypt(tfsImpersonationMap.TargetUserName);
            
            global::TFSBugTracking.TfsImpersonationMap.SetMappings(mappings,usermappingsXml);
        }

        private static string[]  GetUserAndPass(IEnumerable<string> args)
        {
            string [] uap = new string[2];
            foreach (string arg in args)
            {
                if (arg.StartsWith("-u:"))
                {
                    uap[0] = arg.Split(':')[1];
                }
                else if (arg.StartsWith("-p"))
                {
                    uap[1] = arg.Split(':')[1];
                }
            }
            return uap;
        }

        private static void PrintHelp()
        {
            Console.WriteLine("Password Encryption Tool for TFSBugTracking.UserMappings.xml");
            Console.WriteLine("Parameter -? = Show this help");
            //Console.WriteLine("Parameter -f:CustomUserMappings.xml = Uses customusermappings.xml file instead of usermappings.xml");
            Console.WriteLine("Parameter -u:TargetUserName = Selects the target user name to change the password for");
            Console.WriteLine("Parameter -p:TargetPassword = Plain text password of the target user to store encrypted");
            //Console.WriteLine("Parameter -cypherAll = Encrypts all passwords for all users assuming they are all in plain text");
        }
    }
}
